package kibahed.server.schnapsen;

import java.net.Socket;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import kibahed.interfaces.IServerClientConsumer;

public class SchnapsSpielConnecter implements IServerClientConsumer {

	static Map<Socket, Gamer> players = new HashMap<Socket, Gamer>();
	static int counter = 0;

	static Set<Schnapsserver> schnapsserver = new HashSet<Schnapsserver>();
	static Schnapsserver currentServer = null;
	static Map<Gamer, Schnapsserver> connections = new HashMap<Gamer, Schnapsserver>();

	@Override
	public void doSpecificActions(Socket socket, String msg) {
		Gamer player = players.get(socket);
		if (player == null) {
			players.put(socket, new Gamer(socket));
			player = players.get(socket);
		}
		if (msg.startsWith("schnapsen/search")) {
			System.out.println("Searching for game");
			if (connections.get(player) != currentServer||currentServer==null) {
				if (currentServer == null || counter % 2 == 0) {
					System.out.println("Creating new Schnapsserver");
					currentServer = new Schnapsserver("Schnapsen");
					schnapsserver.add(currentServer);
					
				}
				currentServer.setSocket(socket);
				System.out.println("Adding Player "+(counter%2+1) +" to Schnapsserver");
				Schnapsserver oldServer = connections.get(player);
				if (oldServer != null) {
					schnapsserver.remove(oldServer);
					System.out.println("Removing player from old Schnapsserver");
				}
				connections.put(player, currentServer);
				if(counter%2==1){
					currentServer.doSpecificActions(socket, "schnapsen/neuesBummerl");
				}
				
				counter++;
			}

		} else {
			Schnapsserver server = connections.get(player);
			if (server != null) {
				System.out.println("Server do action....->Schnapsserver");
				server.doSpecificActions(socket, msg);
			}
		}

	}

	@Override
	public boolean isAlive() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void setSocket(Socket socket) {

		final Gamer player = new Gamer(socket);
		players.put(socket, player);

	}

}
